package indiwood.controller;

import indiwood.model.ForumVO;
import indiwood.model.service.ForumService;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

@Controller
@RequestMapping("/forum")
public class ForumController extends MultiActionController {
	@Resource(name = "forumServiceImpl")
	private ForumService forumService;

	@RequestMapping(value = "/write.do", method = RequestMethod.POST)
	public ModelAndView write(ForumVO fvo) {
		forumService.write(fvo);
		return new ModelAndView("redirect:/forum/ContentNoHit.do?no="+ fvo.getNo());
	}

	@RequestMapping("/list.do")
	public ModelAndView ForumList(String pageNo) {
		return new ModelAndView("list.forum", "lvo",forumService.ForumList(pageNo));
	}

	@RequestMapping("/write_view.do")
	public ModelAndView write_view() {
		return new ModelAndView("write_view.forum");
	}

	@RequestMapping("/content.do")
	public ModelAndView Content(int no,
			@CookieValue(value = "springboard2", required = false) String cookieValue,
			HttpServletResponse response) {
		ForumVO fvo = null;
		if (cookieValue == null) {
			response.addCookie(new Cookie("springboard2", "|" + no + "|"));
			fvo = forumService.content(no);
			
		} else if (cookieValue.indexOf("|" + no + "|") == -1) {
			// log.info("springboard2 cookie 존재하지만 "+no+"번글은 처음 조회하므로 count증가");
			cookieValue += "|" + no + "|";
			// 글번호를 쿠키에 추가
			response.addCookie(new Cookie("springboard2", cookieValue));
			fvo = forumService.content(no);
		} else {
			// log.info("springboard2 cookie 존재하고 이전에 해당 게시물 읽었으므로 count 증가x");
			fvo = forumService.contentNoHit(no);
		}
		return new ModelAndView("content.forum", "fvo", fvo);
	}
	@RequestMapping("/ContentNoHit.do")
	public ModelAndView ContentNoHit(int no) {
		return new ModelAndView("content.forum", "fvo",forumService.contentNoHit(no));
	}

	@RequestMapping("/forumdelete.do")
	public ModelAndView forumdelete(int no) {
		forumService.forumdelete(no);
		return new ModelAndView("list.forum", "lvo",
				forumService.ForumList("1"));
	}

	@RequestMapping("/updateView.do")
	public ModelAndView updateView(int no) {
		return new ModelAndView("update.forum", "fvo",
				forumService.contentNoHit(no));
	}

	@RequestMapping("/forumUpdate.do")
	public ModelAndView forumUpdate(ForumVO fvo) {
		forumService.forumUpdate(fvo);
		return new ModelAndView("content.forum", "fvo",
				forumService.contentNoHit(fvo.getNo()));
	}
	

}
